package me.kuye.jkuye.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import me.kuye.jkuye.core.Const;

public class PropUtil {
	private Properties properties;

	public PropUtil(String fileName) {
		this(fileName, Const.DEFAULT_ENCODING);
	}

	public PropUtil(File file) {
		this(file, Const.DEFAULT_ENCODING);
	}

	public PropUtil(File file, String defaultEncoding) {
		if (file == null) {
			throw new IllegalArgumentException(" the file can not be null");
		}
		if (file.isFile()) {
			throw new IllegalArgumentException("the file is not found" + file.getName());
		}

		InputStream input = null;
		try {
			input = new FileInputStream(file);
			Properties properties = new Properties();
			properties.load(new InputStreamReader(input));
		} catch (IOException e) {
			throw new RuntimeException("error load in the properties");
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public PropUtil(String fileName, String encoding) {
		InputStream input = null;
		try {
			input = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
			if (input == null) {
				throw new IllegalArgumentException("the file is not found in the classpath :" + fileName);
			}
			properties = new Properties();
			properties.load(new InputStreamReader(input, encoding));

		} catch (IOException e) {
			throw new RuntimeException("error in load the properties ", e);
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public boolean containsKey(String key) {
		return properties.containsKey(key);
	}

	public String get(String key) {
		return properties.getProperty(key);
	}

	public String get(String key, String defaultValue) {
		return properties.getProperty(key, defaultValue);
	}

	public int getInt(String key) {
		return getInt(key, null);
	}

	public int getInt(String key, String defaultValue) {
		String value = properties.getProperty(key);
		return value == null ? Integer.parseInt(defaultValue) : Integer.parseInt(value);
	}

	public long getLong(String key) {
		return getLong(key, null);
	}

	public long getLong(String key, String defaultValue) {
		String value = properties.getProperty(key);
		return value == null ? Long.parseLong(defaultValue) : Long.parseLong(value);
	}

	public boolean getBoolean(String key) {
		return getBoolean(key, null);
	}

	public boolean getBoolean(String key, String defaultValue) {
		String value = properties.getProperty(key);
		return Boolean.parseBoolean(value);
	}

	public Properties getProperties() {
		return properties;
	}
}
